package com.z.admin.controller;

import com.github.pagehelper.PageInfo;
import com.z.base.vo.PageVo;
import com.z.base.vo.Result;
import com.z.base.web.BaseController;
import com.z.blog.entity.Message;
import com.z.blog.service.IMessageService;
import com.z.utils.ImageBase64Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * 留言Controller
 *
 * @author z
 * @date 2022-09-13
 */
@Controller
@RequestMapping("/admin/message")
public class AdminMessageController extends BaseController {

    private String prefix = "admin/message";

    @Autowired
    private IMessageService messageService;

    @GetMapping("/main")
    public String main() {
        return prefix + "/main";
    }

    /**
     * 查询留言列表
     */
    @ResponseBody
    @GetMapping("/data")
    public Result list(@ModelAttribute Message message, PageVo pageVo) {
        PageInfo<Message> pageInfo = messageService.selectMessagePage(message, pageVo);
        pageInfo.getList().forEach(o -> o.setImage(ImageBase64Converter.convertFileToBase64(o.getImage())));
        return Result.table(pageInfo);
    }

    /**
     * 新增留言
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增留言
     */
    @ResponseBody
    @PostMapping("/save")
    public Result save(@RequestBody Message message) {
        return Result.decide(messageService.save(message));
    }

    /**
     * 修改留言
     */
    @GetMapping("/edit")
    public String edit(String id, ModelMap map) {
        Message message =messageService.getById(id);
        map.put("message", message);
        return prefix + "/edit";
    }

    /**
     * 修改留言
     */
    @ResponseBody
    @PutMapping("/update")
    public Result update(@RequestBody Message message) {
        return Result.decide(messageService.updateById(message));
    }

    /**
     * 删除留言
     */
    @ResponseBody
    @DeleteMapping("/batchRemove")
    public Result batchRemove(String ids) {
        return Result.decide(messageService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 删除留言
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") String id) {
        return Result.decide(messageService.removeById(id));
    }
}
